package com.cloudm.technician.ui.base

import android.view.View
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.cloudm.technician.extensions.logger

/**
 * 作者: wesley
 * 时间: 2017/12/27
 * 描述: 地图ui
 */
abstract class BaseMapFragment<T : BasePresenter> : BasePermissionsFragment<T>() {

    protected var lng: Double = 0.0
    protected var lat: Double = 0.0

    private val mClient: AMapLocationClient by lazy {
        AMapLocationClient(mContext.applicationContext).apply {
            setLocationOption(AMapLocationClientOption().apply {
                locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
                isOnceLocation = true
                isNeedAddress = true
            })
            setLocationListener(LocationListener())
        }
    }

    override fun initViews(view: View) {
        requestPermissionsForMap()
    }

    override fun locationGrantedSuccess() {
        super.locationGrantedSuccess()
        mClient.startLocation()
    }

    private inner class LocationListener : AMapLocationListener {
        override fun onLocationChanged(aMapLocation: AMapLocation?) {
            when (aMapLocation?.errorCode) {
                0 -> {
                    lat = aMapLocation.latitude
                    lng = aMapLocation.longitude
                    logger(" lag = $lat lng = $lng")
                }
                else -> logger(
                        "errorCode = ${aMapLocation?.errorCode} errorInfo = ${aMapLocation?.errorInfo}")
            }

            locationSuccess()
        }
    }

    override fun onStop() {
        super.onStop()
        mClient.stopLocation()
    }

    override fun onDestroy() {
        super.onDestroy()
        mClient.onDestroy()
    }

    protected open fun locationSuccess() {

    }
}